package flirtme.activities;

import java.util.ArrayList;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ans.flirtme.R;

import flirtme.constants.Constants;
import flirtme.managers.UserManager;
import flirtme.model.ContactModel;
import flirtme.tools.ChatConnector;

public class ChatActivity extends Activity implements PacketListener {

	private ViewGroup messagesContainer;
	private ScrollView scrollContainer;

	private EditText textMessage;

	String username = null;
	ContactModel dest;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		textMessage = (EditText) this.findViewById(R.id.messageEdit);

		messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
		scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);

		Intent intent = getIntent();

		username = intent.getStringExtra(Constants.USER_NAME);
		UserManager um = UserManager.instance();
		dest = um.getContact(username);

		XMPPConnection con = um.getConnection();

		if (dest != null && con != null) {
			this.addPacketListener(con);
			dest.resetNumberOfMessagesNotReaded();
			this.showPreviousMessages(dest.getMessages());

			// Set a listener to send a chat text message
			Button send = (Button) this.findViewById(R.id.sendButton);
			send.setOnClickListener(onSendMessageClickListener);

		}
	}

	private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			sendMessage();
		}

	};

	private void sendMessage() {
		String text = textMessage.getText().toString();
		UserManager um = UserManager.instance();
		XMPPConnection con = um.getConnection();

		if (con != null & dest != null) {

			Message msg = new Message(dest.getChatEmail(), Message.Type.chat);
			msg.setBody(text);
			con.sendPacket(msg);
			dest.queueMessage(msg);

			showMessage(text, true);
			textMessage.setText("");
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			dest.resetNumberOfMessagesNotReaded();
			removePacketListener();
			this.finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		dest.resetNumberOfMessagesNotReaded();
		removePacketListener();
		super.onBackPressed();
	}

	private void showPreviousMessages(ArrayList<Message> messages) {
		for (Message message : messages) {
			showMessage(message.getBody(),
					message.getTo().equalsIgnoreCase(dest.getChatEmail()));
		}
	}

	private void showMessage(String message, boolean leftSide) {
		final TextView textView = new TextView(ChatActivity.this);
		textView.setTextColor(Color.BLACK);
		textView.setText(message);

		int bgRes = R.drawable.left_message_bg;

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		if (!leftSide) {
			bgRes = R.drawable.right_message_bg;
			params.gravity = Gravity.RIGHT;
		}

		textView.setLayoutParams(params);

		textView.setBackgroundResource(bgRes);

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				messagesContainer.addView(textView);

				// Scroll to bottom
				if (scrollContainer.getChildAt(0) != null) {
					scrollContainer.scrollTo(scrollContainer.getScrollX(),
							scrollContainer.getChildAt(0).getHeight());
				}
				scrollContainer.fullScroll(View.FOCUS_DOWN);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void addPacketListener(Connection connection) {
		if (connection != null) {
			// Add a packet listener to get messages sent to us
			PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
			connection.addPacketListener(this, filter);
		}

	}

	private void removePacketListener() {
		XMPPConnection connection = UserManager.instance().getConnection();
		if (connection != null) {
			connection.removePacketListener(this);
		}
	}

	@Override
	public void processPacket(Packet packet) {
		final Message message = (Message) packet;
		if (message.getBody() != null) {
			String fromFull = StringUtils.parseBareAddress(message.getFrom());
			String fromName = ChatConnector.getUserNameFromChatEmail(fromFull);

			ContactModel cm = UserManager.instance().getContact(fromName);

			cm.queueMessage(message);

			Runnable run = new Runnable() {
				public void run() {
					showMessage(message.getBody(), false);
				}
			};
			this.runOnUiThread(run);

		}
	};
}